'''
Created on 23/03/2009

@author: eh01
'''
from BaseHTTPServer import BaseHTTPRequestHandler
from im.ds import dsconstants
from im.ds.dso import DSO
from im.ds.dst import DST
from im.event import eventconstants
from im.event.event import Event
from im.event.eventmanager import EventManager
import BaseHTTPServer
import datetime
import threading

class IMHTTPRequestHandler(BaseHTTPRequestHandler):
    '''
    HTTPRequestHandler handles all http requests
    '''

    def handle_request(self):
#        print self.headers
#        print 'Start Request: ' + str(datetime.datetime.now())
        dst1 = DST(subject=dsconstants.SUBJECT_ROOT, predicate=dsconstants.PREDICATE_HTTP_REQUEST, literal=self)
        # http://docs.python.org/library/threading.html#id2
        # create a lock initially unlocked.
        lock = threading.Lock()
        lock.acquire()
        # add it to a DST (because an event handler will release it one day) using lock.release()
        dst2 = DST(subject=dsconstants.SUBJECT_ROOT, predicate=dsconstants.PREDICATE_LOCK, literal=lock)
        dso = DSO(dsts=[dst1, dst2])
        event = Event(eventconstants.HTTP_REQUEST_EVENT_TYPE, dso)
        EventManager().add_event(event)
      
        # second acquire(), blocks until the lock.release() called in other thread
        # once the lock has been released, the lock is acquired again
        lock.acquire()
        # call the release immediately, as there is no synchronized code we want to run
        lock.release()
        return
    
    def do_GET(self):        
        self.handle_request()
        return
    
    def do_POST(self):
        self.handle_request()
        return
    
    def do_PUT(self):
        self.handle_request()
        return
    
    def do_DELETE(self):
        self.handle_request()
        return